"use strict";

import {
  config,
  dbData,
  rss,
  session
} from "./instances";
/**
 * @class RokidApp
 */
class Main {
  /**
   * @method constructor
   * @param {Object} event
   * @param {Object} context
   * @param {Object} callback
   */
  constructor() {
    this._event = null;
    this._context = null;
    this._callback = null;
    this._rokid = null;

    // TODO: 暂未使用
    // 流程阶段: 0进行中，1结束，2已经提交结束
    this._stage = config.STAGEINIT;

    this._executants = {};
    this._ttsStrArr = []; // 本次请求的tts内容
  }

  init(event, context, callback) {
    if (event && context && callback) {
      this._event = event;
      this._context = context;
      this._callback = callback;
      this._rokid = Rokid.handler(event, context, callback);
      if (config.debug) {
        console.debug("[Main]", "Rokid init success.");
      }
    }
  }

  // 加载并注册 handers
  registerHandlers(executants) {
    let self = this;
    this._executants = Object.assign(this._executants, executants);
    if (config.debug) {
      for (const key in this._executants) {
        if (this._executants.hasOwnProperty(key)) {
          console.debug("[RegHandler]", key, "has added.");
        }
      }
    }

    let handlers = {};
    for (const key in this._executants) {
      if (this._executants.hasOwnProperty(key)) {
        handlers[key] = function () {
          let holder = this;
          self.go(holder, key);
        };
      }
    }

    this._rokid.registerHandlers(handlers);
  }

  // 启动 Rokid
  execute() {
    this._rokid.execute();
  }

  // 获取用户 ID
  getUserID() {
    let userID = Rokid.param.context.user.userId;
    if (!userID) {
      userID = "test_user_id";
    }
    return userID;
  }

  // 设置 tts, 会清空之前已经添加的 tts
  setTtsStr(str) {
    this._ttsStrArr = [str];
  }

  // 追加 tts
  addTtsStr(str) {
    this._ttsStrArr.push(str);
  }

  // 获取 tts
  getTtsStr(str) {
    let res = this._ttsStrArr.join("");
    if (str) {
      res += str;
    }
    return res;
  }

  // TODO: 暂未使用
  emit(holder, action, msg) {
    holder.emit(action, msg);
  }

  // yes or no 问答确认
  YON(intent) {
    let acts = ["是的", "取消"];
    return {
      confirmIntent: intent,
      confirmSlot: "yes_or_no",
      optionWords: ["是的", "取消"],
      retryTts: config.tpls.retryWithActionTips.format({
        action: acts.join("、")
      })
    };
  }

  // hander 执行调度：删除自动加载 db、session等逻辑，只做分发
  go(holder, handleName) {
    let self = this;
    let handle = null;
    console.debug("[GoStart]", handleName);
    new Promise((resolve, reject) => {
        // 分发
        if (self._executants.hasOwnProperty(handleName)) {
          handle = self._executants[handleName];
          session.setHolder(holder);
          resolve(self._executants[handleName]);
        } else {
          reject("can not get executant");
        }
      })
      .then(result => {
        console.debug("[GoExec]", handleName);
        return handle(holder);
      })
      .then(result => {
        console.debug("[GoSuccess]", handleName, result);
        dbData.submit();
        return holder.emit(result);
      })
      .catch(e => {
        console.debug("[GoError]", handleName, e);
        holder.setTts({
          tts: "服务器错误，请稍后重试。"
        });
        holder.emit(":error", e);
      });
  }
  // hander 执行调度
  // go(holder, handleName) {
  //   let self = this;
  //   let handle = null;
  //   console.debug("[GoStart]", handleName);
  //   new Promise((resolve, reject) => {
  //     // 分发
  //     if (self._executants.hasOwnProperty(handleName)) {
  //       handle = self._executants[handleName];
  //       session.setHolder(holder);
  //       resolve(self._executants[handleName]);
  //     } else {
  //       reject("can not get executant");
  //     }
  //   })
  //     // 加载
  //     .then(result => {
  //       // 加载 rss.config
  //       rss.setConfig({
  //         mode: session.get("rss.config.mode")
  //       });
  //       // 加载数据库数据
  //       return dbData.reload();
  //     })
  //     .then(result => {
  //       console.debug("[GoExec]", handleName);
  //       // return handle(holder);
  //       let handleRes = ':done';
  //       return handle(holder).then(result => {
  //         handleRes = result;
  //         if (["rss.channel.go", "rss.pager", "rss.play"].contains(handleName)) {
  //           // session.set("handle_now", handleName);
  //           dbData.sessionSet("handle_now", handleName);
  //         }
  //         session.submit();
  //         return dbData.submit().then(result => {
  //           console.debug("[GoExec Submit]", handleName);
  //           return handleRes;
  //         });
  //       });
  //     })
  //     .then(result => {
  //       console.debug("[GoSuccess]", handleName, result);
  //       holder.emit(result);
  //     })
  //     .catch(e => {
  //       console.debug("[GoError]", handleName, e);
  //       holder.setTts({
  //         tts: "服务器错误，请稍后重试。"
  //       });
  //       holder.emit(":error", e);
  //     });
  // }
}

export default Main;
